package com.doge.util.typeHandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import lombok.SneakyThrows;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @program: doge
 * @description: 将 admin/admin/list 中的 orderid 字符串转换为 整数数组
 * @author: Keyu Li
 * @create: 2021-11-29 22:10
 **/

@MappedTypes(Integer[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class Str2IntsTypeHandler extends BaseTypeHandler<Integer[]> {

    ObjectMapper mapper = new ObjectMapper();
    /**
     * 输入映射： Integer[] ---> String
     * @param ps:   预编译sql语句
     * @param index: 为预编译sql语句提供参数的占位符序号
     * @param parameter: 输入映射传入的值
     * @param jdbcType:
     * @return void
     * @date 11/30/2021 10:08
     */
    @SneakyThrows
    @Override
    public void setNonNullParameter(PreparedStatement ps, int index, Integer[] parameter, JdbcType jdbcType) throws SQLException {
        // json
        String result = mapper.writeValueAsString(parameter);
        ps.setString(index,result);
    }

    @Override
    public Integer[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        // 得到 [1,2.3,4]
        String result = rs.getString(columnName);
        return transferStoI(result);
    }

    @Override
    public Integer[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String result = rs.getString(columnIndex);
        return transferStoI(result);

    }

    @Override
    public Integer[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String result = cs.getString(columnIndex);
        return transferStoI(result);

    }

    @SneakyThrows
    private Integer[] transferStoI(String result){
        Integer[] ints = mapper.readValue(result, Integer[].class);
        return ints;
    }
}
